import cv2
import numpy as np
import os,sys


def detect_differences(src_path, dst_path,color_img,isfilter=False,threshold=60):
    # 对原始图像和目标图像进行高斯模糊，以减少噪声影响
    kernel=(5,5)
    src_img = cv2.GaussianBlur(cv2.imread(src_path,cv2.IMREAD_GRAYSCALE), kernel, 0)
    dst_img = cv2.GaussianBlur(cv2.imread(dst_path,cv2.IMREAD_GRAYSCALE), kernel, 0)

    # 计算两张图像的差异（绝对差）
    diff = cv2.absdiff(src_img, dst_img)

    # 对差异图进行二值化处理，设定一个阈值来区分差异和背景
    _, binary_diff = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)

    # 查找差异区域的轮廓
    contours, _ = cv2.findContours(binary_diff, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # contours, _ = cv2.findContours(binary_diff, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    

    # 在原图上绘制矩形框标记差异区域
    # for cnt in contours:
    #     x, y, w, h = cv2.boundingRect(cnt)
    #     cv2.rectangle(color_img, (x, y), (x + w, y + h), (0, 255, 0), 2)


    # 定义排除区域 (x1, y1, x2, y2)
    exclude_zone = (800, 800, 2200, 2100)
    zone_contours = []

    for contour in contours:
        if not isfilter:
            x, y, w, h = cv2.boundingRect(contour)
            cv2.rectangle(color_img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 检查是否与排除区域重叠
        else:
            if not (x < exclude_zone[2] and x + w > exclude_zone[0] and y < exclude_zone[3] and y + h > exclude_zone[1]):
                zone_contours.append(contour)
                cv2.rectangle(color_img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    return color_img



def defect_detect():

    image3 = cv2.imread('defect/0_1_0.jpg')
    h,w= image3.shape[:2]

    # image3 = cv2.cvtColor(image3, cv2.COLOR_BGR2RGB)
    # image3 = image3[:,:,0]

    # 调用函数进行差异检测和标注
    result = detect_differences('defect/0_0_0.jpg', 'defect/0_1_0.jpg',image3,False,30)

    # 显示结果
    # cv2.imshow('Defect Detection Result', result)
    cv2.imwrite(f'd:/result.jpg',result)
    # cv2.imshow(f'{w}:{h}', image3)
    cv2.waitKey(0)
    cv2.destroyAllWindows()



def split_pic(path:str,split_px_width=5):
    img=cv2.imread(path)
    h,w=img.shape[:2]

    sw= int((w-split_px_width)/2)
    print(sw*2,w)
    left_half = img[:, :sw]
    right_half=img[:,sw+split_px_width:w]

    cv2.imwrite(f'd:/left.jpg',left_half)
    cv2.imwrite(f'd:/right.jpg',right_half)

    pass


def zc(src:str,splitwidth=4):
    dst_path=f'd:/result_cz.jpg'
    split_pic(src,splitwidth)
    src_img=cv2.imread(f'd:/left.jpg')
    dst_img=detect_differences(f'd:/left.jpg',f'd:/right.jpg',src_img,False,30)
    cv2.imwrite(dst_path,dst_img)
    os.system(dst_path)
    pass



def getAppendPath(src:str,append:str)->str:
    arr=src.split('.')
    return f'{arr[0]}_{append}.{arr[1]}'

def candyTest(src:str):
    img_color=cv2.imread(src)
    img=cv2.imread(src,cv2.IMREAD_GRAYSCALE)
    dst=getAppendPath(src,'gray')
    cv2.imwrite(dst,img)

    lk= cv2.Canny(img,80,200)
    dst=getAppendPath(dst,'canny')


    kernel = np.ones((5, 19), np.uint8)
    closing = cv2.morphologyEx(lk, cv2.MORPH_CLOSE, kernel)
    opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)

    contours, _ = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # 此处应包含筛选轮廓并定位车牌的代码逻辑
    rects=[]
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        rects.append((x,y,w,h))
        # cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 0), 2)
    rect=max(rects,key=lambda _:_[2])
    x, y, w, h=rect
    # cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 0), 2)
    # cv2.imwrite(dst,img_color)

    img_cut= img_color[y:y+h,x:x+w]
    dst=getAppendPath(src,'cut')
    cv2.imwrite(dst,img_cut)




    # max(contours)

    # x=[{'a': 10, 'b': 1, 'c': 100}, {'a': 1000, 'b': 1, 'c': 100}]
    # y=list(filter(lambda _:_['a']==10,x))
    # z=max(x,key=lambda _:_['a'])
    # print(y,z)





    # cv2.imshow('gray',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    pass


def cpsb(src:str):
    img=cv2.imread(src)
    h,w=img.shape[:2]
    b,g,r=cv2.split(img)
    # cv2.imshow("Blue Channel (Gray)", b)
    # cv2.imshow("Green Channel (Gray)", g)
    # cv2.imshow("Red Channel (Gray)", r)

    x = b.copy()
    for i in range(h):
        for j in range(w):
            x[i,j]=0


    x.resize(h*3,w)
    x[h:2*h,0:w]=g
    x[2*h:3*h,0:w]=r
    # cv2.imshow('stack',x)
    cv2.imwrite('d:/xx.jpg',x)

    cv2.waitKey(0)
    cv2.destroyAllWindows()
    pass



# defect_detect()
# os.system(f'd:/result.jpg')

# zc(f'd:/10.jpg')
# cpsb(r'D:\cp\1.jpg')
candyTest(r'e:\cp.jpg')
# candyTest(r'D:\result.jpg')

print('ok')